package cn.xuziao.databasecourse.tools;


import cn.xuziao.databasecourse.pojo.FeedBacKInfo;
import lombok.extern.slf4j.Slf4j;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;

@Slf4j
public class SendIdentifyingCode {

    public static void send(String address, String content) {
        Properties prop = new Properties();
        prop.setProperty("mail.host", "smtp.qq.com");
        prop.setProperty("mail.transport.protocol", "smtp");
        prop.setProperty("mail.smtp.auth", "true");
        prop.setProperty("mail.smtp.port", "465");
        prop.setProperty("mail.smtp.ssl.enable", "true");

        Session session = Session.getInstance(prop);
        session.setDebug(true);
        Transport ts = null;
        try {
            ts = session.getTransport();
            ts.connect("smtp.qq.com", "greenorangestack@foxmail.com", "jppdelxzytmugfhd");
            Message message = createSimpleMail(session, address, content);
            ts.sendMessage(message, message.getAllRecipients());
        } catch (MessagingException e) {
            e.printStackTrace();
        } finally {
            try {
                assert ts != null;
                ts.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }

    private static MimeMessage createSimpleMail(Session session, String address, String content) throws MessagingException {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("greenorangestack@foxmail.com"));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(address));
        message.setSubject("伽卡他卡小组邮件");
        message.setContent(content, "text/html;charset=UTF-8");
        return message;
    }

    public static String format(FeedBacKInfo feedBacKInfo) {
        String msg = "<html lang=\"en\">" +
                "<head>" +
                "    <meta charset=\"UTF-8\">" +
                "    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">" +
                "    <title>Document</title>" +
                "</head>" +
                "<body>" +
                "    <b>提交者姓名：</b>%{name}%" +
                "    <br><b>提交者邮箱：</b>%{email}%" +
                "    <br><b>提交的题目：</b><font color='red'>%{title}%" +
                "    </font><br><b>详情:</b>%{info}%" +
                "</body>" +
                "</html>";
        msg = msg.replace("%{name}%", feedBacKInfo.getFirstName()+" "+feedBacKInfo.getLastName());
        msg = msg.replace("%{email}%", feedBacKInfo.getMail());
        msg = msg.replace("%{title}%", feedBacKInfo.getTitle());
        msg = msg.replace("%{info}%", feedBacKInfo.getInformation());
        log.info(msg);
        return msg;
    }

}

